import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.Timer;


public class CPU {
	// 1 second delay on system timer.
	private static final int DELAY = 100;
	// address of next instruction.
	private int pc = 0;
	// process control Block
	
	// System Timer
	Timer myTimer;
	// Scheduler
	Sched scheduler;
	// Current Process
	Process currentProcess;
	

	// creates and starts system timer
	public CPU() {
		scheduler = new Sched();
		currentProcess = scheduler.getNextProcess(Sched.caller.TIMER);
		myTimer = new Timer(DELAY, new ActionListener() {
		
		@Override
		public void actionPerformed(ActionEvent arg0) {
			
			timerInterrupt();
		}
		});
		myTimer.start();
			
	}
	
	
	
	protected void setCurrentProcess(Process proc) {
		currentProcess = proc;
	}
	
	protected int pcInc(Process proc) {
		pc = (proc.fetchnxtStep() + 1) % proc.fetchnoStep();
		
		if(pc == 0) {
			timerInterrupt();
			myTimer.restart();
		}
		return pc;
	}
	
	
	
	protected void timerInterrupt() {
		System.out.println("Device 0 (System Timer) produced an interrupt.");
		currentProcess.changePriority();
		scheduler.addProcess(currentProcess, pc);
		
		
		setCurrentProcess(scheduler.getNextProcess(Sched.caller.TIMER));
		pc = currentProcess.fetchnxtStep();
	}
	
	public void runProcess() {
		
		pcInc(currentProcess);
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CPU cpu = new CPU();
		
		int i = 0;
		while(i == 0) {
			cpu.runProcess();
		}
		
		
	}

}
